/**
 *
 *	Depends on:
 *		jQuery
 *		jQuery UI
 */
$(document).ready(function() {

	//Selectors and Statics
	var QUESTION_LIST = $('#admin-question-list');
	var FORM = $('#reorder-question-form');

	var ERROR_MESSAGE = $('<div id="reorder-error" class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;</button><strong>Error!</strong> Unable to save the new question order.</div>');

	//init
	if(QUESTION_LIST.length) {
		QUESTION_LIST.sortable({
	      placeholder: "admin-question-placeholder",
	      forcePlaceholderSize: true,
	      opacity: 0.6,
	      handle: '.admin-question-handle',
	      update: rearrangeQuestions
	    });
	}

	/**
	 *	Sends transform to exercise request with ajax.
	 */
	function rearrangeQuestions() {
		$.ajax({
			type: 'POST',
			url: FORM.attr('action'),
			data: {'question-structure': QUESTION_LIST.sortable( "serialize", { key: "question" } )},
			dataType: 'HTML',
			success: ajaxSuccess,
			error: ajaxError
		});
	}

	/**
	 * Called upon ajax success
	 */
	function ajaxSuccess(response) {
		error = $('#reorder-error');
		if(error.length) {
			error.remove();
		}
	}

	/**
	 * Called upon ajax error
	 */
	function ajaxError(response) {
		if(! $('#reorder-error').length) {
			FORM.append(ERROR_MESSAGE);
		}
	}	

});